package com.android.vgongyi.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.WeakHashMap;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.image.CacheTask;
import com.android.image.TPManager;
import com.android.vgongyi.R;
import com.android.vgongyi.common.AppConstant;
import com.android.vgongyi.utils.SystemUtil;
import com.ant.liao.GifView;
import com.ant.liao.GifView.GifImageType;

public class SaveImageActivity extends BaseActivity{
		
	private Button       backBtn;
	private Button       saveBtn;
	private String       picturename;
	private String       url;
	private String 		 img_extension;
	private String       imageHeight;
	private String       imageWidth;
	private ImageView    imageView;
	private GifView      gifView;
	private TPManager    tm;
	private WeakHashMap<String, WeakReference<InputStream>> mImageCache = new WeakHashMap<String, WeakReference<InputStream>>();
	
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);	
		setContentView(R.layout.save_image);

		imageView     = (ImageView) this. findViewById(R.id.ImageView_save);
		saveBtn       = (Button)this.findViewById(R.id.Common_refresh);
		backBtn       = (Button) this.findViewById(R.id.Common_back);
		gifView       = (GifView) findViewById(R.id.save_weibo_gifview);
		
		
		saveBtn.setText(R.string.save);
		saveBtn.setVisibility(View.VISIBLE);	
		backBtn.setVisibility(View.VISIBLE);
		
		
		Intent intent = getIntent();
		url           = intent.getStringExtra("imageUrl");
//		url = "http://shouji.ci77.com/public/attachement/1204/24/b99723c34c02a836f940.gif";
		img_extension = intent.getStringExtra("img_extension");
//		img_extension = "gif";
		imageHeight   = intent.getStringExtra("imageHeight");
		imageWidth    = intent.getStringExtra("imageWidth");	
		float big_h   = Float.valueOf(imageHeight);
		float big_w   = Float.valueOf(imageWidth);
		
		tm 			  = TPManager.getInstance();
		
		picturename   = URLEncoder.encode(url);

		if(big_h>0){
		
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(SystemUtil.getImageWidthSize(this),SystemUtil.getImageHeightSize(this, big_h, big_w));
			imageView.setLayoutParams(params);
		
		}
		if(!img_extension.equals("gif")){
			imageView.setVisibility(View.VISIBLE);
			gifView.setVisibility(View.GONE);
			tm.addTask( new CacheTask(url,imageView));
			
		}else{
		   try {
			   
				imageView.setVisibility(View.GONE);
				gifView.setVisibility(View.VISIBLE);
				String dir  = AppConstant.IMAGE_PATH + "/";
				String name = URLEncoder.encode(url);
				String path = new StringBuffer().append(dir).append(name).toString();
				
				WeakReference<InputStream> reference = mImageCache.get(path);
				if(reference!=null&&reference.get()!=null){
					gifView.setGifImage(reference.get());
					gifView.setGifImageType(GifImageType.COVER);
				}else{
					File file = new File(path);
					InputStream input = new FileInputStream(file);
					mImageCache.put(path, new WeakReference<InputStream>(input));
					gifView.setGifImage(input);
					gifView.setGifImageType(GifImageType.COVER);
				}
				
			} catch (Exception e){
				Toast.makeText(getApplicationContext(),"显示出错", Toast.LENGTH_SHORT).show();
			}
		}
		saveBtn.setOnClickListener(new OnClickListener(){      
			
			private boolean flag = false;;
			
				public void onClick(View v) {
						
					try {
						if(flag) return ;
						flag = true;
						savePicture();
						flag = false;
						Toast.makeText(getApplicationContext(), R.string.save_image_success, Toast.LENGTH_SHORT).show();
						
					} catch (Exception e) {
						flag = false;
						Toast.makeText(getApplicationContext(), R.string.save_image_failed, Toast.LENGTH_SHORT).show();
					};
				}
		});
		
		backBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {

				SaveImageActivity.this.finish();
				
			}
		});		
	}
	
	@Override
	protected void onStop() {
		try{
			gifView.destroy();
		}catch (Exception e) {

		}
		super.onStop();
	}
	
	private void savePicture() throws Exception{
		String favPath  = Environment.getExternalStorageDirectory().getAbsolutePath() + "/VGongyi/Favourite";
		String commPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/VGongyi/imagefiles";
		
		File favFileDir  = new File(favPath);
		File commFileDir = new File(commPath);
		
		if (!favFileDir.exists())  favFileDir .mkdirs();
		if (!commFileDir.exists()) commFileDir.mkdirs();;
		
		File favFile  = new File(favPath,picturename);
		File commFile = new File(commPath,picturename);
		
		if(commFile.exists()){
			
			InputStream  in  = new FileInputStream(commFile);
			
			OutputStream out = new FileOutputStream(favFile);
			
			byte[] buffer = new byte[1024];
			
			while(in.read(buffer)!=-1){
				out.write(buffer);
			}
			
			in.close();
			out.flush();
			out.close();
		}
		
	}
	
}
